﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Ex11.ReverseWords
{
    class ReverseWords
    {
        static string RemoveWhiteSpace(Match match)
        {
            string word = match.Value;
            return word.TrimStart();
        }

        static string ToUpperFirstLetter(Match match)
        {
            string word = match.Value;
            return Char.ToUpper(word[0]) + word.Substring(1);
        }

        static string ToLowerFirstLetter(Match match)
        {
            string word = match.Value;
            return Char.ToLower(word[0]) + word.Substring(1);
        }

        static string ReverseSentence(string sentence)
        {
            MatchCollection words = Regex.Matches(sentence, @"\w+|,");
            StringBuilder result = new StringBuilder();
            for (int i = words.Count - 1; i >= 0; i--)
            {
                result.Append(words[i] + " ");
            }
            string newSentence = Regex.Replace(result.ToString(), @"\s,", RemoveWhiteSpace);
            return newSentence.TrimEnd() + ".";
        }

        static void Main(string[] args)
        {
            string originalSentence = "This is a good test, with comma.";
            string reversedSentence = ReverseSentence(originalSentence);
            reversedSentence = Regex.Replace(reversedSentence, @"\w+.", ToLowerFirstLetter);
            reversedSentence = Regex.Replace(reversedSentence, @"\A\w+", ToUpperFirstLetter);
            Console.WriteLine(reversedSentence);
        }
    }
}
